package com.example.lets;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import cn.bmob.v3.BmobUser;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FullUserActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_full_user);
		
		// 获取上一个页面传来的用户列表
		Intent in = this.getIntent();
		ArrayList<User> users = (ArrayList<User>) getIntent().getSerializableExtra("users");
		
		// 加载用户至界面
		ListView listView = (ListView) FullUserActivity.this.findViewById(R.id.full_user_list);
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

		for (User user : users) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("UserPicFileName", user.getPicFilename());
			map.put("UserName", user.getNickname());
			String tag = "";
			if (!user.getTag1().equals("")) {
				tag += user.getTag1();
				if (!user.getTag2().equals("")) {
					tag += "; " + user.getTag2();
					if (!user.getTag3().equals(""))
						tag += "; " + user.getTag3();
				}
			}
			map.put("UserTag", tag);
			listItem.add(map);
		}

		listView.setAdapter(new FullUserAdapter(FullUserActivity.this, listItem));
		
		// 返回按钮事件注册
		Button back = (Button) this.findViewById(R.id.full_user_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				FullUserActivity.this.finish();				
			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.full_user, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

    @Override
    public void onBackPressed() {
        finish();
        return;
    }
}

class FullUserAdapter extends BaseAdapter {
	
	private LayoutInflater mInflater; // 得到一个LayoutInfalter对象用来导入布局
	private ArrayList<HashMap<String, Object>> list; // 用于存放要显示的数据列表
	private Context context;
 
    public FullUserAdapter(Context context, ArrayList<HashMap<String, Object>> list) {
        this.mInflater = LayoutInflater.from(context);
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size(); // 返回数组的长度        
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
         
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        
    	final FullUserHolder holder;
        // 观察convertView随ListView滚动情况
        Log.v("MyListViewBase", "getView " + position + " " + convertView);
        if (convertView == null) {
        	
            convertView = mInflater.inflate(R.layout.listview_user_full, null);
            holder = new FullUserHolder();

            // 得到各个控件的对象                    
            holder.name  = (TextView)  convertView.findViewById(R.id.UserName);
            holder.tag   = (TextView)  convertView.findViewById(R.id.UserTag);
            holder.image = (ImageView) convertView.findViewById(R.id.UserImage);
            
            // 绑定ViewHolder对象
            convertView.setTag(holder); 
        }
        else{
            holder = (FullUserHolder) convertView.getTag(); //取出ViewHolder对象                  
        }
        
        // 设置TextView显示的内容，即我们存放在动态数组中的数据   
        holder.name.setText(list.get(position).get("UserName").toString());
        holder.tag.setText(list.get(position).get("UserTag").toString());
        
        // 下载活动图片至本地
        String fileName = (String) list.get(position).get("UserPicFileName");
        
		// 检查是否已存在活动图片的缓存
        User curUser = BmobUser.getCurrentUser(context, User.class);
        String cachePath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + fileName;
        
        if ((new File(cachePath)).exists()) { // 缓存存在直接加载
        	
            Log.i("bmob", "成功加载缓存：" + cachePath);
            Bitmap bm = BitmapFactory.decodeFile(cachePath);
            holder.image.setImageBitmap(bm);
            String str = BmobPro.getInstance(context).getCacheDownloadDir();
            Log.i("bmob", str);
            
        } else { // 缓存不存在需要从远程下载
        	
        	BTPFileResponse response = BmobProFile.getInstance(context).download(fileName, new DownloadListener() {

                @Override
                public void onSuccess(String fullPath) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "下载成功：" + fullPath);
                    Bitmap bm = BitmapFactory.decodeFile(fullPath);
                    holder.image.setImageBitmap(bm);
                    String str = BmobPro.getInstance(context).getCacheDownloadDir();
                    Log.i("bmob", str);
                }

                @Override
                public void onProgress(String localPath, int percent) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "download-->onProgress :" + percent);
                }

                @Override
                public void onError(int statuscode, String errormsg) {
                    // TODO Auto-generated method stub
                    Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
                    Toast.makeText(context, "下载出错："+ statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
                }
    		});
        }
        
        return convertView;
    }


 
}

// 存放控件
class FullUserHolder {
    public ImageView image;
    public TextView  name;
    public TextView  tag;
}

